<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = [
       'category_id', 'category_parent_id', 'recommend_position_id', 'title', 'author', 'image', 'douban_score', 'store',
        'intro', 'catalog', 'deleted', 'real_user_read_num', 'total_read_num', 'on_sale'
    ];

    public static function boot()
    {
        parent::boot();
        static::saving(function($model){
            if(empty($model->on_sale))
            {
                $model->on_sale = 1;
            }
        });
    }

    public function book_publish_info()
    {
        return $this->hasOne(BookPublishInfo::class);
    }

    public function scopeOnSale($query, $on_sale)
    {
        if (!in_array($on_sale, [1,2])) {
            return $query;
        }

        return $query->where('on_sale',  $on_sale);
    }

    public function comments()
    {
        return $this->hasMany(BookComment::class)->where('deleted',0);
    }

    public function book_lists()
    {
        return $this->belongsToMany(BookList::class,'book_list_book_relations','book_id');
    }

    public function book_recommend_positions()
    {
        return $this->belongsToMany(BookRecommendPosition::class,'book_recommend_position_relations','book_id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id');
    }

    public function parent_catgeory()
    {
        return $this->belongsTo(Category::class,'category_parent_id');
    }

    //减去库存
    public function decreaseStore()
    {
        $this->increment('real_user_read_num');
        $this->increment('total_read_num');
        return $this->newQuery()->where('id', $this->id)->where('store', '>=', 1)->decrement('store');
    }

    //增加库存
    public function addStore()
    {
        $this->increment('store');
    }
}
